#!/usr/bin/python3
#    this file is part from ucc

#    Copyright (c) 2018 - 2019 Hayder Majid <hayder@riseup.net>
#    This Program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU  General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    This Program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import gi, sys, webbrowser, inspect, os
from signal import signal, SIGINT, SIG_DFL
from subprocess import Popen
gi.require_version('WebKit', '3.0')
from gi.repository import WebKit, Gtk
#check python version 
try:
    from urllib.request import urlopen, pathname2url
except ImportError:
    from urllib import urlopen, pathname2url


loc = os.path.expanduser("/etc/default/locale")

class UccView(WebKit.WebView):
    def __init__(self):
        WebKit.WebView.__init__(self)

        self.connect('navigation-policy-decision-requested', self._policy)
        self.l_uri = None

    def _policy(self, view, frame, net_req, nav_act, pol_dec):
        uri = net_req.get_uri()

        try:
            if uri.index('#') > 0:
                uri = uri[:uri.index('#')]
        except ValueError:
            pass

        if uri == self.l_uri:
            pol_dec.use()
            return True

        if uri.startswith('run://'):
            self._exec(uri)
            return True

        self.l_uri = uri

        page = urlopen(uri)
        frame.load_string(page.read().decode("utf-8"), "text/html", 
            "utf-8", page.geturl())
        pol_dec.ignore()
        return True

    def _exec(self, uri):

        if uri.startswith('run://'):
            uri = uri[6:]

        if uri == 'synaptic':
            if os.path.exists("/usr/bin/synaptic-pkexec"):
                Popen(['usudo ', 'synaptic'])
            else:
                      print('synaptic not installed'.format(uri))

        if uri == 'uruk-software-center':
            if os.path.exists("/usr/bin/uruk-software-center-pkexec"):
                Popen(['usudo ', 'uruk-software-center'])
            else:
                      print('uruk software center not installed'.format(uri))
                      
        if uri == 'gparted':
            if os.path.exists("/usr/bin/gparted-pkexec"):
                Popen(['usudo ', 'gparted'])
            else:
                      print('gparted not installed'.format(uri))
                      
        elif uri == 'keyboard-properties':
            Popen(['/bin/sh', '-c','mate-keyboard-properties'])  
                                
        elif uri == 'language-selector':
            Popen(['/bin/sh', '-c','lucale'])                      
    
        elif uri == 'accessibility':
            Popen(['/bin/sh', '-c','mate-at-properties'])
            
        elif uri == 'users':
            Popen(['/bin/sh', '-c','users-admin'])

        elif uri == 'firewall':
            Popen(['/bin/sh', '-c','gufw'])
            
        elif uri == 'cleaner':
            Popen(['/bin/sh', '-c','uruk-cleaner'])
                       
        elif uri == 'user':
            Popen(['/bin/sh', '-c','mate-about-me'])
            
        elif uri == 'network':
            Popen(['/bin/sh', '-c','caja --no-desktop network:'])
            
        elif uri == 'connection':
            Popen(['/bin/sh', '-c','nm-connection-editor'])
            
        elif uri == 'display':
            Popen(['/bin/sh', '-c','mate-display-properties'])
 
        elif uri == 'shared':
            Popen(['/bin/sh', '-c','shares-admin'])
           
            
        elif uri == 'appearance':
            Popen(['/bin/sh', '-c','mate-appearance-properties'])

        elif uri == 'mate-tweak':
            Popen(['/bin/sh', '-c','mate-tweak'])

        elif uri == 'backup':
            Popen(['/bin/sh', '-c','deja-dup'])
            
        elif uri == 'default-applications-properties':
            Popen(['/bin/sh', '-c','mate-default-applications-properties'])
            
        elif uri == 'desktop':
            Popen(['/bin/sh', '-c','caja-file-management-properties'])
            
        elif uri == 'notification-properties':
            Popen(['/bin/sh', '-c','mate-notification-properties'])
            
        elif uri == 'screensaver-preferences':
            Popen(['/bin/sh', '-c','mate-screensaver-preferences'])
            
        elif uri == 'window-properties':
            Popen(['/bin/sh', '-c','mate-window-properties'])
            
        elif uri == 'time':
            Popen(['/bin/sh', '-c','time-admin'])
            
            
        elif uri == 'mouse':
            Popen(['/bin/sh', '-c','mate-mouse-properties'])
   
        elif uri == 'power':
            Popen(['/bin/sh', '-c','mate-power-preferences'])

        elif uri == 'power-statistics':
            Popen(['/bin/sh', '-c','mate-power-statistics'])

        elif uri == 'blueman':
            Popen(['/bin/sh', '-c','blueman-manager'])

        elif uri == 'mate-session-properties':
            Popen(['/bin/sh', '-c','mate-session-properties'])
            
        elif uri == 'software-properties':
            Popen(['/bin/sh', '-c','updater'])
            
        elif uri == 'scan':
            Popen(['/bin/sh', '-c','simple-scan'])
            
        elif uri == 'printer':
            Popen(['/bin/sh', '-c','system-config-printer'])
            
        elif uri == 'notification-properties':
            Popen(['/bin/sh', '-c','mate-notification-properties'])
            
        elif uri == 'sound':
            Popen(['/bin/sh', '-c','pavucontrol'])
	    
        elif uri == 'login-settings':
            Popen(['/bin/sh', '-c','lightdm-gtk-greeter-settings-pkexec'])
	    
        elif uri == 'home_page':
            Popen(['exo-open', 'https://urukproject.org'])

        elif uri == 'close':
            Gtk.main_quit()

        elif uri.startswith("link?"):
            open_new_tab(uri[5:])

        else:
            print('Unknown command: {}'.format(uri))


class UccApp(object):
    def __init__(self):
        self._location = os.path.dirname(os.path.abspath(inspect.getfile(
            inspect.currentframe())))
        if os.path.exists(os.path.join(self._location, 'data/')):
            print('Using relative path for data source. Non-production testing.')
            self._data_path = os.path.join(self._location, 'data/')
        elif os.path.exists('/usr/share/ucc/frontend/mate/'):
            if 'LANG="ar' in open(loc).read():
                print('Using /usr/share/ucc/frontend/mate/local/ar/ path.')
                self._data_path = '/usr/share/ucc/frontend/mate/local/ar/'
            else :
                print('Using /usr/share/ucc/frontend/mate/local/en/ path.')
                self._data_path = '/usr/share/ucc/frontend/mate/local/en'
        else:
            print('Unable to source the ucc data directory.')
            exit(1)

        self._new_window()

    def _new_window(self):
        w = Gtk.Window()
        w.set_position(Gtk.WindowPosition.CENTER)
        w.set_wmclass('Uruk Control Center', 'Uruk Control Center')
        w.set_title('Uruk Control Center')
        w.set_size_request(768, 496)
        w.set_icon_from_file(os.path.join(self._data_path, "/usr/share/pixmaps/ucc.svg"))
        mv = UccView()
        file_out = os.path.abspath(os.path.join(self._data_path, 'index.html'))

        uri = 'file://' + pathname2url(file_out)
        mv.open(uri)
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        sw.add(mv)
        b = Gtk.VBox(homogeneous=False, spacing=0)
        b.pack_start(sw, expand=True, fill=True, padding=0)
        w.add(b)
        w.connect('delete-event', self.close)
        w.show_all()

        self._window = w
        self._appView = mv

    def run(self):
        signal(SIGINT, SIG_DFL)
        Gtk.main()

    def close(self, p1, p2):
        Gtk.main_quit(p1, p2)

app = UccApp()
app.run()
